package cc.vv.baselibrary.view.webview;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.widget.LinearLayout;

import java.util.ArrayList;

import cc.vv.baselibrary.R;
import cc.vv.baselibrary.util.LKCommonUtil;
import cc.vv.baselibrary.util.LKLogUtil;
import cc.vv.baselibrary.util.StringProcessingUtil;
import cc.vv.baselibrary.util.router.RouterActivityIntentResourceKey;
import cc.vv.baselibrary.util.router.RouterTransferCenterUtil;
import cc.vv.baselibrary.vFinal.BTParamKey;
import cc.vv.baselibrary.view.jzvd.JZVideoPlayer;
import cc.vv.baselibrary.view.jzvd.JZVideoPlayerStandard;
import cc.vv.baselibrary.view.webview.bean.H5ContentBeanObj;

/**
 * webView视频混合View
 *
 * @author zhaoleilei on 2018/1/15.
 */

public class WebViewMixVideoView extends LinearLayout {
    /**
     * 上下文
     */
    private Context mContext;

    /**
     * 根布局
     */
    private LinearLayout ll_mixRootView;

    /**
     * 根布局
     */
    private LayoutInflater layoutInflater;

    /**
     * view
     */
    private View mView;

    /**
     * newH5data
     */
    private ArrayList<H5ContentBeanObj> newContent;

    /**
     * BCWebView集合
     */
    private ArrayList<BCWebView> bcWebViewList;

    /**
     * Video集合
     */
    private ArrayList<JZVideoPlayerStandard> videoPlayerStandardList;

    /**
     * 页面数据加载完成后是否已经回调（只能加载一次）
     */
    private boolean canLoadFinishCallBack;

    /**
     * H5所有图片集合
     */
    private ArrayList<String> allImgUrl;

    /**
     * 所有webView加载完成回调
     */
    private OnAllViewLoadingFinish viewLoadingFinishCallBack;

    public WebViewMixVideoView(Context context) {
        this(context, null);
    }

    public WebViewMixVideoView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public WebViewMixVideoView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        initView();
    }

    /**
     * 初始化view
     */
    private void initView() {
        layoutInflater = LayoutInflater.from(mContext);
        mView = layoutInflater.inflate(R.layout.layout_linetext_ltextview, null);
        ll_mixRootView = (LinearLayout) mView.findViewById(R.id.ll_lineTextRoot);
//        LK.view().inject(this, mView);
        this.addView(mView);
        newContent = new ArrayList<>();
        bcWebViewList = new ArrayList<>();
        videoPlayerStandardList = new ArrayList<>();
        canLoadFinishCallBack = true;
    }

    /**
     * 封装H5数据分割成WebView和Video
     *
     * @param originH5Content 原始H5数据
     */
    public void packageH5Data(String originH5Content) {
        if (TextUtils.isEmpty(originH5Content)) {
            return;
        }
        allImgUrl = StringProcessingUtil.getImgUrls(originH5Content);
        if (!originH5Content.startsWith("<p>")) {
            originH5Content = "<p>" + originH5Content + "</p>";
        }
        while (originH5Content.contains("<iframe") && originH5Content.contains("</iframe>")) {
            originH5Content = splitData(originH5Content);
        }
        if (!"<p></p>".equals(originH5Content)) {
            H5ContentBeanObj h5ContentBeanObj = new H5ContentBeanObj();
            h5ContentBeanObj.setUrl(originH5Content);
            h5ContentBeanObj.setLoadUp(false);
            newContent.add(h5ContentBeanObj);
        }
        addView();
    }

    /**
     * 重复分割WebView和Video数据
     *
     * @param originData H5数据
     */
    private String splitData(String originData) {
        if (TextUtils.isEmpty(originData)) {
            return originData;
        }
        String end = null;
        try {
            String begin = originData.substring(0, originData.indexOf("<iframe")) + "</p>";
            if (!"<p></p>".equals(begin)) {
                H5ContentBeanObj h5ContentBeanObj = new H5ContentBeanObj();
                h5ContentBeanObj.setUrl(begin);
                h5ContentBeanObj.setLoadUp(false);
                newContent.add(h5ContentBeanObj);
            }
            String videoH5 = originData.substring(originData.indexOf("<iframe"), originData.indexOf("</iframe>") + "</iframe>".length());
            String videoSrc = videoH5.substring(videoH5.indexOf("src=\"") + "src=\"".length());
            String videoUrl = videoSrc.substring(0, videoSrc.indexOf("\""));
            H5ContentBeanObj h5ContentBeanObj = new H5ContentBeanObj();
            h5ContentBeanObj.setUrl(videoUrl);
            h5ContentBeanObj.setLoadUp(false);
            newContent.add(h5ContentBeanObj);
            end = "<p>" + originData.substring(originData.indexOf("</iframe>") + "</iframe>".length());
        } catch (Exception e) {
            LKLogUtil.e(e.getMessage(), e);
        }
        return end;
    }

    /**
     * 动态加载布局
     */
    private void addView() {
        if (newContent != null && newContent.size() > 0) {
            ll_mixRootView.removeAllViews();
            for (int i = 0; i < newContent.size(); i++) {
                final int index = i;
                if (newContent.get(i).getUrl().contains("<p>")) {
                    final BCWebView bcWebView = new BCWebView(mContext);

                    //获取webView图片url并注入
                    ArrayList<String> imageUrls = StringProcessingUtil.getImgUrls(newContent.get(i).getUrl());
                    if (imageUrls != null && imageUrls.size() > 0) {
                        try {
                            bcWebView.addJavascriptInterface(new MJavascriptInterface(mContext, imageUrls), "imgListener");
                        } catch (Exception e) {
                            LKLogUtil.e(e.getMessage(), e);
                        }
                    }
                    //获取所点击图片url的另一种方式
//                    bcWebView.setOnLongClickListener(new OnLongClickListener() {
//                        @Override
//                        public boolean onLongClick(View v) {
//                            WebView.HitTestResult hitTestResult = bcWebView.getHitTestResult();
//                            switch (hitTestResult.getType()){
//                                case WebView.HitTestResult.IMAGE_TYPE:
//                                    LKToastUtil.showToastShort("ok");
//                                    break;
//
//                            }
//                            return false;
//                        }
//                    });

                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
                    bcWebView.setLayoutParams(params);
                    bcWebView.loadDataWithBaseURL(null, newContent.get(i).getUrl(), "text/html", "utf-8", null);
                    ll_mixRootView.addView(bcWebView);
                    if (bcWebViewList != null) {
                        bcWebViewList.add(bcWebView);
                    }

                    bcWebView.setLoadCallBack(new BCWebView.LoadCallBack() {
                        @Override
                        public void onLoadingFinished() {

                        }

                        @Override
                        public void onLoadingFinished(String content) {

                        }

                        @Override
                        public void onLoadingFinished(WebView view, String url) {
                            newContent.get(index).setLoadUp(true);
                            showVideo(true);
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    jsImageClickListener(bcWebView);
                                }
                            }, 200);
                        }
                    });
                } else {
                    JZVideoPlayerStandard videoPlayerStandard = new JZVideoPlayerStandard(mContext);
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LKCommonUtil.dip2px(184));
                    videoPlayerStandard.setLayoutParams(params);
                    videoPlayerStandard.setVisibility(INVISIBLE);
                    String url = newContent.get(index).getUrl();
//                    Bitmap bitmap = ImageUtil.getVideoThumbnail(url);
//                    if(bitmap!=null){
//                        videoPlayerStandard.thumbImageView.setImageBitmap(bitmap);
//                    }
                    videoPlayerStandard.setUp(url, JZVideoPlayer.NORMAL_ORIENTATION);
                    ll_mixRootView.addView(videoPlayerStandard);
                    if (videoPlayerStandardList != null) {
                        videoPlayerStandardList.add(videoPlayerStandard);
                    }
                }
            }
            if (!isHaveWebView(newContent)) {
                showVideo(false);
            }
        }
    }

    /**
     * 显示视频
     *
     * @param isHaveH5 是否还有webView还是纯视频
     */
    private void showVideo(boolean isHaveH5) {
        if (isHaveH5) {
            boolean isLoadUp = isLoadUp(newContent);
            if (isLoadUp) {
                if (getViewLoadingFinishCallBack() != null && canLoadFinishCallBack) {
                    getViewLoadingFinishCallBack().onAllViewLoadingFinish();
                    canLoadFinishCallBack = false;
                }
                if (videoPlayerStandardList != null) {
                    for (int i = 0; i < videoPlayerStandardList.size(); i++) {
                        videoPlayerStandardList.get(i).setVisibility(VISIBLE);
                    }
                }
            }
        } else {
            if (getViewLoadingFinishCallBack() != null && canLoadFinishCallBack) {
                getViewLoadingFinishCallBack().onAllViewLoadingFinish();
                canLoadFinishCallBack = false;
            }
            if (videoPlayerStandardList != null) {
                for (int i = 0; i < videoPlayerStandardList.size(); i++) {
                    videoPlayerStandardList.get(i).setVisibility(VISIBLE);
                }
            }
        }
    }

    /**
     * 销毁当前界面加载的webView,防止内存溢出
     */
    public void destroyWebView() {
        if (bcWebViewList != null) {
            for (int i = 0; i < bcWebViewList.size(); i++) {
                if (bcWebViewList.get(i) != null) {
                    try {
                        bcWebViewList.get(i).loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
                        bcWebViewList.get(i).clearHistory();
                        ll_mixRootView.removeView(bcWebViewList.get(i));
                        bcWebViewList.get(i).destroy();
                        bcWebViewList.set(i, null);
                    } catch (Exception e) {
                        LKLogUtil.e(e.getMessage(), e);
                    }
                }
            }
            bcWebViewList = null;
        }
        if (videoPlayerStandardList != null) {
            for (int i = 0; i < videoPlayerStandardList.size(); i++) {
                try {
                    ll_mixRootView.removeView(videoPlayerStandardList.get(i));
                } catch (Exception e) {
                    LKLogUtil.e(e.getMessage(), e);
                }
            }
            videoPlayerStandardList = null;
            ll_mixRootView = null;
            mView = null;
        }

        if (allImgUrl != null) {
            allImgUrl = null;
        }
        if (newContent != null) {
            newContent = null;
        }
    }


    /**
     * 获取点击的图片url位置
     *
     * @param imgUrl 图片url
     */
    private int getPosition(String imgUrl) {
        if (allImgUrl != null && (!TextUtils.isEmpty(imgUrl))) {
            for (int i = 0; i < allImgUrl.size(); i++) {
                if (imgUrl.equals(allImgUrl.get(i))) {
                    return i;
                }
            }
        }
        return 0;
    }

    /**
     * 图片注入监听
     *
     * @param webView webView
     */
    private void jsImageClickListener(WebView webView) {
        webView.loadUrl("javascript:(function(){" +
                "var objs = document.getElementsByTagName('img'); " +
                "for(var i=0;i<objs.length;i++) " +
                "{" +
                " objs[i].onclick=function() " +
                " { " +
                " window.imgListener.fullScreenImage(this.src); " +
                " } " +
                "}" +
                "})()");
    }

    /**
     * 图片点击注入回调
     */
    public class MJavascriptInterface {
        private Context context;
        private ArrayList<String> imageUrls;

        public MJavascriptInterface(Context context, ArrayList<String> imageUrls) {
            this.context = context;
            this.imageUrls = imageUrls;
        }

        @android.webkit.JavascriptInterface
        public void fullScreenImage(String imgUrl) {
            int position = getPosition(imgUrl);
            if (allImgUrl != null && allImgUrl.size() > 0) {
//                Intent intent = new Intent(mContext, BCImageDisplayActivity.class);
//                intent.putExtra(BCImageDisplayActivity.UrlsLogo, allImgUrl);
//                intent.putExtra(BCImageDisplayActivity.CurrentPositionLogo, position);
//                mContext.startActivity(intent);
                Intent routerIntent = RouterTransferCenterUtil.getInstance().getRouterIntent(context,
                        RouterActivityIntentResourceKey.KEY_BT_IMAGE_WATCHER_ACTIVITY);
                routerIntent.putStringArrayListExtra(BTParamKey.INTENT_IMGS_URLS, allImgUrl);
                routerIntent.putExtra(BTParamKey.INTENT_IMGS_POSITION, position);
                RouterTransferCenterUtil.getInstance().routerStartActivity(context, routerIntent);
            }
        }
    }

    /**
     * 获取WebView加载完成回调
     */
    public interface OnAllViewLoadingFinish {
        void onAllViewLoadingFinish();
    }


    /**
     * 获取WebView的加载回调方法对象
     */
    public OnAllViewLoadingFinish getViewLoadingFinishCallBack() {
        return viewLoadingFinishCallBack;
    }

    /**
     * 设置WebView的加载回调方法对象
     */
    public void setViewLoadingFinishCallBack(OnAllViewLoadingFinish viewLoadingFinishCallBack) {
        this.viewLoadingFinishCallBack = viewLoadingFinishCallBack;
    }

    /**
     * 获取整个布局
     *
     * @return ll
     */
    public LinearLayout getLl_mixRootView() {
        return ll_mixRootView;
    }


    /**
     * 判断是否还有bcWebView数据
     */
    public boolean isHaveWebView(ArrayList<H5ContentBeanObj> data) {
        if (data != null && data.size() > 0) {
            for (int i = 0; i < data.size(); i++) {
                if (data.get(i).getUrl().contains("<p>")) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断所有bcWebView是否加载完数据
     */
    public boolean isLoadUp(ArrayList<H5ContentBeanObj> data) {
        if (data != null && data.size() > 0) {
            for (int i = 0; i < data.size(); i++) {
                if (data.get(i).getUrl().contains("<p>") && (!data.get(i).isLoadUp())) {
                    return false;
                }
            }
        }
        return true;
    }
}
